iT邦幫忙

0

[筆記][JavaScript] - 隨機取出陣列元素之值

  • 分享至 

  • xImage
  •  

目的:能產生簡易版本亂數抽籤系統

先從 Math.random() 語法了解

再帶入至 Math.floor() 讓每個被取出物件機率都相同

再用 Javascript 把對應的 array 元素取出顯示在指定標籤中

Math.random()

會回傳介於0到1之間(包含 0,不包含1) 的偽隨機數字

大致符合數學與統計上的均勻分佈

function getRandom() {
  return Math.random();
}

//此方法不符合加密學安全性要求。請勿使用於任何加密、資安相關領域。
//詳請請見:https://zhuanlan.zhihu.com/p/205359984

隨機取出兩數值之間值(不包含最大值)

The returned value is no lower than (and may possibly equal) min, and is less than (and not equal) max.

返回的值大於等於 最小值 min,且小於 最大值 max

e.g A, B, C, D, E, F, G

回傳數值區間包含A,不包含G

function getRandomArbitrary(min, max) {
  return Math.random() * (max - min) + min;
}

Math.floor()

將所有的小數無條件捨去到比該值小的最大整數

有點繞口但其實就是高斯符號的取底

console.log(Math.floor(5.9999));
// expected output: 5

console.log(Math.floor(-5.05));
// expected output: -6

所以結合起來 Math.floor(Math.random()*7-0 + 0);

會回傳 0 到 6 (包含0跟6)其中一個『整數』

每個數字選中機率都一樣,所以可以拿來做抽籤

那個數字七也就代表陣列的長度

第幾位抽到就是 回傳值+1

Math.ceil()

取大於的最小整數

console.log(Math.ceil(.95));
// expected output: 1

console.log(Math.ceil(4));
// expected output: 4

首尾數值都包含且取整數

例如取得 4.9 到 9.9 之間的一個整數
5,6,7,8,9

整數用 floor, 包含最大值 +1

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  // min = 5     
  max = Math.floor(max);
  // max = 9 
  return Math.floor(Math.random() * (max - min + 1) + min); 
    // Math.floor(Math.random()*5 + 5
}

假設有一陣列

array=[one,two,three,four];

隨機取出一位即為

<p id="demo0"></p>
<p id="demo1"></p>

randomData()

function randomData(){

let x = Math.floor(Math.random() * data.length);
let y = x + 1;
document.getElementById("demo0").innerHTML = "第幾位:" + y;
document.getElementById("demo1").innerHTML = "中獎人:" + array[x];
}

效果預覽:https://wastu01.github.io/Javascript-Random-from-array/

完整程式碼:https://codepen.io/mrwang01/pen/jOYbXQQ

以上同步至個人學習日誌:https://hackmd.io/@DCT/隨機亂數抽籤系統

參考資料:

Math.random()語法說明:
https://developer.mozilla.org/zh-TW/docs/Web/JavaScript/Reference/Global_Objects/Math/random

用Math.random()取得亂數的技巧
https://ithelp.ithome.com.tw/articles/10197904#=

<< 我的第一篇it邦文章 :) >>


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言